<template>
  <div class="goodsDetailBar">
    <div class="goodsTypeItem" v-for="(item,index) in showGoodsDetail" :key="index">
      <div class="item-left">
        {{item.title}}
      </div>
      <div class="item-right">
        <span :class="{selectedSpan: sub.selected}" v-for="(sub,indexs) in item.subTitle" :key="indexs" @click="handDetailClick(item.title,sub.title)">
          {{sub.title}}
        </span>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex';
export default {
  name: 'GoodsDetailBar',
  props: {
    currentTypes: {
      type: String,
      default: ''
    }
  },
  computed: {
    ...mapState({
      goodsDetail: state => state.index.goodsDetail
    }),
    showGoodsDetail () {
      this.goodsDetail.forEach(item => {
        item.subTitle.forEach(items => {
          if (items.title === '全部') {
            items.selected = true;
          } else {
            items.selected = false;
          }
        })
      });
      this.$emit('getSelectItem', []);
      const tempARR = [...this.goodsDetail];
      if (this.currentTypes === '2') {
        return tempARR.slice(0, 3);
      } else if (this.currentTypes === '3') {
        return tempARR.slice(0, 3).concat(tempARR[4]);
      } else if (this.currentTypes === '4') {
        return tempARR.slice(0, 4);
      }
      return this.goodsDetail;
    }
  },
  methods: {
    ...mapMutations(['saveGoodsDetail']),
    handDetailClick (key1, key2) {
      this.goodsDetail.forEach(item => {
        item.subTitle.forEach(items => {
          if (item.title === key1 && items.title === key2) {
            if (items.title !== '全部') {
              item.subTitle[0].selected = false;
              items.selected = !items.selected;
            } else {
              item.subTitle[0].selected = true;
              item.subTitle.slice(1).forEach(s => {
                s.selected = false;
              })
            }
          }
        })
      });
      const list = [];
      this.goodsDetail.forEach(item => {
        item.subTitle.forEach(items => {
          if (items.selected === true && items.title !== '全部') {
            list.push(items.title)
          }
        })
      });
      this.saveGoodsDetail(list);
      this.$emit('Search',list.length !== 0);
    },
  },
  watch: {
    goodsDetail: {
      handler(newV){
        newV.forEach((item,index) => {
          let arr = [];
          item.subTitle.forEach((s,i) => {
            if(i > 0){
              arr.push(s.selected);
            }
          });
          item.subTitle[0].selected = !arr.reduce((a,b) => a||b);
        })
      },
      deep: true
    }
  }
}
</script>
<style lang="scss" src='./index.scss' scoped />